<?php

class PublicController extends Controller {
	public function login() {
		if ($this->isGet ()) {
			$this->display ();
		} else {
			$map = array ();
			$map ['username'] = $_POST ['username'];
			$admin = M ( 'Admin' )->where ( $map )->find ();
			if (empty ( $admin )) {
				echo '用户名或密码不正确';
			} else {
				if ($admin ['password'] != md5 ( $_POST ['password'] )) {
					echo '用户名或密码不正确';
				} else if ($admin ['is_forbid'] == "1") {
					echo '账号已禁用';
				} else {
					// 更新管理员最后登录时间和ip
					$data ['id'] = $admin ['id'];
					$data ['last_login_time'] = $_SERVER['REQUEST_TIME'];
					$data ['last_login_ip'] = get_client_ip();
					M ( 'Admin' )->update ( $data );
					// 更新菜单
					$configmenuList = require CONFIG_PATH . '/config.menu.php';
					$roleMenuList = M ( 'RoleMenu' )->field ( 'menu_id', true )->where ( "role_id={$admin['role_id']}" )->select ();
					$menuList = $accessList = array ();
					foreach ( $configmenuList as $menu ) {
						$m = array ();
						foreach ( $menu ['children'] as $item ) {
							if (in_array ( $item ['id'], $roleMenuList )) {
								$accessList [$item ['name']] = $item ['url'];
								if (! isset ( $item ['is_hidden'] ) || $item ['is_hidden'] == false) {
									$m [] = $item;
								}
							} else if (isset ( $item ['is_open'] ) && $item ['is_open'] == true) {
								if (isset ( $item ['is_hidden'] )) {
									if ($item ['is_hidden'] == false) {
										$m [] = $item;
									}
								} else {
									$m [] = $item;
								}
								$accessList [$item ['name']] = $item ['url'];
							}
						}
						if (! empty ( $m )) {
							$l ['name'] = $menu ['name'];
							$l ['children'] = $m;
							$menuList [] = $l;
						}
					}
					$_SESSION ['accessList'] = $accessList;
					$_SESSION ['menuList'] = $menuList;
					$_SESSION ['admin'] = $admin;
					echo 'true';
				}
			}
		}
	}
	public function layout(){
		$_SESSION=null;
		session_destroy();
		$this->redirect('Public/login');
	}
	/**
	 * 上传缩略图
	 */
	public function upload() {
		$upload = new UploadFile (); // 实例化上传类
		$rs=array();
		if (! $upload->upload (UPLOAD_PATH.'/')) { // 上传错误提示错误信息
			$rs['status']=false;
			$rs['error_message']=$upload->getErrorMsg ();
		} else { // 上传成功
			$rs['status']=true;
			$rs['fileInfo']=$upload->getUploadFileInfo();
			$rs['fileInfo']=$rs['fileInfo']['0'];
		}
		echo json_encode($rs);
	}
	public function isUsernameExists(){
		$username=filter_trim($_GET['username']);
		$user=M('Admin')->where("username='{$username}'")->isExists();
		if($user){
			echo 'false';
		}else{
			echo 'true';
		}
	}
}